from .db import *
import traceback


def execute_task_wrapper(task_func):
    """装饰器用于处理错误并适当更新任务状态"""
    def wrapper(*args, **kwargs):
        try:
            return task_func(*args, **kwargs)
        except Exception as e:
            job_id = kwargs.get('job_id',None)
            job_execution_id = kwargs.get('job_execution_id',None)
            test_cases = kwargs.get('test_cases',None)
            sync_case = kwargs.get('sync_case',None)
            executor = kwargs.get('executor',None)
            update_job(job_id, status=Status.BLOCK.value, percentage=100,
                       detail=traceback.format_exc(), finished=datetime.now())
            if job_execution_id is not None:
                update_execution(job_execution_id,
                                 status=Status.BLOCK.value, finished=datetime.now())
            raise  # Re-throw the exception after handling for further logging or debugging
    return wrapper


def execute_testcase_wrapper(testcase_func):
    """装饰器用于处理错误并适当更新用例状态"""
    def wrapper(*args, **kwargs):
        try:
            return testcase_func(*args, **kwargs)
        except Exception as e:
            testcase = kwargs.get('testcase', None)
            if testcase:
                print(testcase[0])
                update_execution_case(
                    testcase[0], status=Status.BLOCK.value, detail=traceback.format_exc(), finished=datetime.now())
            raise  # Re-raise exception after handling
    return wrapper


def execute_step_wrapper(step_func):
    """装饰器用于处理错误并适当更新步骤状态"""
    def wrapper(*args, **kwargs):
        try:
            step = step_func(*args, **kwargs)
        except Exception as e:
            step = kwargs.get('step', None)
            step['result'] = Result.BLOCK.value
            if 'detail' not in step:
                step['detail'] = ''
            step['detail'] += str(e) + "\n" + traceback.format_exc()
    return wrapper


def handle_execute_commnad_remotely(func):
    """装饰器用于执行远程命令并捕捉异常"""
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as e:
            # 可以根据实际需求记录日志或者更新测试结果状态等
            print(f"Error during remote execution: {str(e)}")
            return None
    return wrapper
